package com.example.orderservice.service;

import com.example.orderservice.event.OrderCreatedEvent;
import com.example.orderservice.model.Inventory;
import com.example.orderservice.model.Order;
import com.example.orderservice.repository.InventoryRepository;
import com.example.orderservice.repository.OrderRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private InventoryRepository inventoryRepository;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    private static final String ORDER_CHANNEL = "order-created-channel";

    public Order createOrder(Long userId, String items) {
        // 1. 检查库存
        List<String> itemList = Arrays.asList(items.split(",\\s*"));
        for (String item : itemList) {
            Inventory inventory = inventoryRepository.findByItemName(item);
            if (inventory == null) {
                throw new RuntimeException("Item " + item + " not found in inventory!");
            }
            if (inventory.getQuantity() <= 0) {
                throw new RuntimeException("Item " + item + " is out of stock!");
            }
        }

        // 2. 创建订单
        Order order = new Order();
        order.setUserId(userId);
        order.setItems(items);
        order.setStatus("CREATED");
        order.setCreatedAt(LocalDateTime.now());
        order = orderRepository.save(order);

        // 3. 发布订单创建事件
        OrderCreatedEvent event = new OrderCreatedEvent(order.getId(), userId, items);
        try {
            String eventJson = objectMapper.writeValueAsString(event);
            redisTemplate.convertAndSend(ORDER_CHANNEL, eventJson);
            System.out.println("Published event: " + eventJson);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return order;
    }

    public List<Order> getAllOrders() {
        return orderRepository.findAll();
    }
}